import { RoleModel } from '../../schemas/system/Role';
import { Role } from '../../types';
import { HttpError } from '../../exceptions/HttpError';

export class RoleRepository {
  // 获取所有字典项
  async findAll(): Promise<Role[]> {
    try {
      return await RoleModel.find().sort({ type: 1, sort: 1, createdAt: -1 }).populate('tenantId createdBy updatedBy type').lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`获取角色列表失败: ${error.message}`);
    }
  }



  // 根据ID获取菜单
  async findById(id: string): Promise<Role | null> {
    try {
      const role = await RoleModel.findById(id).lean().populate('tenantId').populate('tenantId createdBy updatedBy type').lean();
      if (!role) {
        throw HttpError.notFound('角色不存在');
      }
      return role;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取角色信息失败: ${error.message}`);
    }
  }

  // 根据类型查找字典项
  async findByType(type: string): Promise<Role[] | null> {
    try {
      return await RoleModel.find({ type }).sort({ sort: 1 }).populate('tenantId createdBy updatedBy type').lean();
    } catch (error: any) {
      throw HttpError.internalServerError(`查找角色失败: ${error.message}`);
    }
  }

  // 创建用户
  async create(roleData: Partial<Role>): Promise<Role> {
    try {
      const role = new RoleModel(roleData);
      return await role.save();
    } catch (error: any) {
      if (error.code === 11000) {
        throw HttpError.unprocessableEntity('角色已存在', error.errors);
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败1', error.errors);
      }
      throw HttpError.internalServerError(`创建角色失败2: ${error.message}`);
    }
  }

  // 更新用户
  async update(id: string, roleData: Partial<Role>): Promise<Role | null> {
    try {
      // 移除密码字段，防止通过更新接口修改密码
      const { ...updateData } = roleData;

      const role = await RoleModel.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      );
      if (!role) {
        throw HttpError.notFound('角色不存在');
      }

      return role;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      if (error.code === 11000) {
        throw HttpError.conflict('角色已存在');
      }
      if (error.name === 'ValidationError') {
        throw HttpError.unprocessableEntity('数据验证失败', error.errors);
      }
      throw HttpError.internalServerError(`更新角色失败: ${error.message}`);
    }
  }

  // 删除用户
  async delete(id: string): Promise<boolean> {
    try {
      const result = await RoleModel.findByIdAndDelete(id);
      if (!result) {
        throw HttpError.notFound('角色不存在');
      }
      return true;
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除角色失败: ${error.message}`);
    }
  }

  // 获取用户数量
  async count(): Promise<number> {
    try {
      return await RoleModel.countDocuments();
    } catch (error: any) {
      throw HttpError.internalServerError(`统计角色数量失败: ${error.message}`);
    }
  }

  // 分页查询用户
  async findWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Role[], page: number, limit: number, total: number, pages: number }> {
    try {
      const skip = (page - 1) * limit;
      const [list, total] = await Promise.all([
        RoleModel.find().sort({ createdAt: -1 }).skip(skip).limit(limit).populate('tenantId createdBy updatedBy type').lean(),
        RoleModel.countDocuments()
      ]);

      return {
        list,
        total,
        page,
        limit,
        pages: Math.ceil(total / limit)
      };
    } catch (error: any) {
      throw HttpError.internalServerError(`分页查询角色失败: ${error.message}`);
    }
  }
}

export default new RoleRepository();
